package la.iok.hzsvn.lewin.movie.service;

import la.iok.hzsvn.lewin.movie.config.DfsProperties;
import la.iok.hzsvn.lewin.movie.core.exception.ErrorCode;
import la.iok.hzsvn.lewin.movie.entity.AppFile;
import la.iok.hzsvn.lewin.movie.entity.AppPackageItem;
import la.iok.hzsvn.lewin.movie.mapper.AppFileMapper;
import la.iok.hzsvn.share.annotations.NotNull;
import la.iok.hzsvn.share.dfs.model.DfsDescriptor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

@Service
public class AppFileServiceImpl extends MovieFileServiceImpl<AppFile, AppFileMapper> implements AppFileService {

    public AppFileServiceImpl(AppFileMapper mapper, WebDfsService webDfsService, DfsProperties dfsProperties) {
        super(mapper, webDfsService, dfsProperties);
    }

    @Override
    public void downloadFile(HttpServletResponse response, Long fileId) {
        AppFile file = select(fileId);
        ErrorCode.APP_FILE_NOT_EXIST.assertNotNull(file,fileId);
        DfsDescriptor descriptor = webDfsService.dfsFile(file.getPath());
        ErrorCode.APP_FILE_NOT_EXIST.assertTrue(webDfsService.exist(descriptor),file.getPath());
        webDfsService.downloadFile(response,descriptor,file.getFileName());
    }

    @Override
    protected void validateReference(@NotNull AppFile file) {
        AppPackageItem item = executeSelect(AppPackageItem.class,"select * from "
                + AppPackageItem.class.getSimpleName() + " where fileId=" + file.getId() + " limit 1");
        ErrorCode.FILE_REFERENCED_BY_OTHER.assertNull(item,file.getPath(),AppPackageItem.class.getSimpleName());
    }
}
